package xcmg.device.infra.interceptor.externalApiCheck;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xcmg.device.infra.annotation.ExternalApiRequest;
import xcmg.device.infra.interceptor.externalApiCheck.handle.ApiCheckStrategy;


/**
 *  外部调用备件接口拦截校验，使用时在对应的controller方法上加注解@ExternalApiRequest，
 *  注解参数为ApiCheckOptionEnum，用于标记校验的方案，不给参数默认为方案1，即通过秘钥时间戳等MD5加密的方式校验
 *  具体见对应处理中的说明与逻辑
 *
 * @author wangyong
 */
@Component
public class ExternalApiInterceptor  extends HandlerInterceptorAdapter {

  @Autowired
  private ApiCheckStrategy apiCheckStrategy;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //如果不是controller中 @RequestMapping注解的方法则直接通过
    if (!handler.getClass().isAssignableFrom(HandlerMethod.class)) {
      return true;
    }
    HandlerMethod method = (HandlerMethod)handler;
    // 方法未加注解直接通过
    ExternalApiRequest apiCheckRequest = method.getMethodAnnotation(ExternalApiRequest.class);
    if (null == apiCheckRequest){
      return true;
    }
    return apiCheckStrategy.checkHandle(request, response, apiCheckRequest.value());
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    super.postHandle(request, response, handler, modelAndView);
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    super.afterCompletion(request, response, handler, ex);
  }

  @Override
  public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    super.afterConcurrentHandlingStarted(request, response, handler);
  }
}
